<!-- 账户管理-用户管理-新增或编辑用户信息 -->
<template>
  <div class="main-app">
    <el-page-header @back="cancel" :content="title" style="margin: 1%;"></el-page-header>
    <div style="margin-top: 25px; margin-left: 1%;">({{$t('common.title.tipLeft')}}<span style="color: red">*</span>{{$t('common.title.tipRight')}})</div>
    <el-row style="margin-top: 10px">
      <el-form ref="form" :model="form" :rules="rules" style="width: 50%; margin-left: 25%" label-width="15%">
        <el-form-item :label="$t('common.label.accountNumber')" prop="accountNumber" required>
          <el-input v-model="form.accountNumber" />
        </el-form-item>
        <el-form-item :label="$t('common.label.phone')" prop="phone" required>
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item :label="$t('common.label.name')" prop="name" required>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item :label="$t('common.label.sex')" required>
          <el-radio-group v-model="form.sex">
            <el-radio :label="0">{{$t('common.label.man')}}</el-radio>
            <el-radio :label="1">{{$t('common.label.woman')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('common.label.roleName')" required>
          <el-select v-model="form.roleName" :placeholder="$t('common.placeholder.pleaseSelect')" style="width: 100%" @change="roleChange">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.label.jobNumber')" prop="jobNumber">
          <el-input v-model="form.jobNumber" />
        </el-form-item>
        <el-form-item :label="$t('common.label.email')" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item :label="$t('common.label.status')" required>
          <el-radio-group v-model="form.status">
            <el-radio :label="0">{{$t('common.label.enable')}}</el-radio>
            <el-radio :label="1">{{$t('common.label.disable')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('common.label.remark')" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
      </el-form>
    </el-row>
    <el-row style="margin-top: 40px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="info" plain @click="cancel">{{$t('common.button.cancel')}}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isLoading" @click="save">{{$t('common.button.save')}}</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import {
  SubmitUser,
  UserDetail
} from "../../../api/user.js";
import {
  RoleList
} from "../../../api/role.js";

export default {
  // 页面公共变量
  data() {
    return {
      isLoading: false,       // 是否显示加载框
      title: "",              // 顶部标题
      id: "",                 // 编辑数据的主键ID
      roleList: [],           // 角色下拉框数据源
      // 提交表单内容
      form: {
        sex: 0,
        roleId: 0,
        roleName: "",
        status: 0,
      },
      // 表单验证项配置
      rules: {
        accountNumber: [{required:true, message:this.$t('common.prompt.rules.accountNumber'), trigger:"blur"}],
        phone: [
          {required:true, message:this.$t('common.prompt.rules.phone'), trigger:"blur"},
          {min:11, max:11, message:this.$t('common.prompt.rules.phoneLength'), trigger:"blur"}
        ],
        name: [{required:true, message:this.$t('common.prompt.rules.name'), trigger:"blur"}],
        role: [{required:true, message:this.$t('common.prompt.rules.role'), trigger:"change"}]
      },
    };
  },
  // 页面创建完成事件
  async created() {
    // 接收路由传递的参数
    const { id } = this.$route.params;

    // 动态设置标题
    if(id === undefined) {
      this.title = this.$t('common.title.addUser');
    } else {
      this.title = this.$t('common.title.editUser');
    }

    // 将接收到的数据填充至页面公共变量
    this.id = id;

    // 获取详情数据
    await this.getDataInfo(id);
  },
  // 页面相关方法
  methods: {
    // 获取详情数据
    async getDataInfo(id) {

      // 获取全部角色数据
      await RoleList({
        Page: null,
        Limit: null,
        Status: "0"
      }).then((data) => {
        // 设置数据源
        this.roleList = data.data;

        // 默认设置为第一个数据
        this.form.roleId = this.roleList[0].id;
        this.form.roleName = this.roleList[0].name;
      });

      // 获取详情数据
      const { data } = await UserDetail({
        Id: id
      });
      if (data) {
        // 处理部分字段
        data.sex = parseInt(data.sex);
        if (data.sex !== 1) {
          data.sex = 0;
        }
        data.status = parseInt(data.status);
        data.roleId = parseInt(data.roleId);

        // 设置表单数据
        this.form = data;
      }
    },
    // 角色下拉框选择事件
    roleChange(val){
      let obj = this.roleList.find(item => item.id === val);
      if (obj) {
        this.form.roleId = obj.id;
        this.form.roleName = obj.name;
      } else {
        this.form.roleId = '';
        this.form.roleName = '';
      }
    },
    // 保存数据事件
    save() {
      // 校验必填项
      this.$refs["form"].validate(async (valid) => {
        // 如果表单校验成功时执行
        if (valid) {
          let data = {};

          // 填充表单数据
          let message = "";

          if (this.id) {
            data = {
              UserData: {
                id: this.id,
                Name: this.form.name,
                Sex: this.form.sex.toString(),
                RoleId: this.form.roleId.toString(),
                RoleName: this.form.roleName,
                JobNumber: this.form.jobNumber,
                AccountNumber: this.form.accountNumber,
                Phone: this.form.phone,
                Email: this.form.email,
                status: this.form.status.toString(),
                Remark: this.form.remark
              }
            };
            message = this.$t('common.prompt.success.edit');
          } else {
            data = {
              UserData: {
                Name: this.form.name,
                Sex: this.form.sex.toString(),
                RoleId: this.form.roleId.toString(),
                RoleName: this.form.roleName,
                JobNumber: this.form.jobNumber,
                AccountNumber: this.form.accountNumber,
                Phone: this.form.phone,
                Email: this.form.email,
                status: this.form.status.toString(),
                Remark: this.form.remark
              }
            };
            message = this.$t('common.prompt.success.add');
          }

          // // 测试：查看已生成的表单内容，不提交数据
          // console.log(data)
          // return;

          // 打开加载框
          this.isLoading = true;

          // 提交数据
          const { success, msg } = await SubmitUser(data);

          // 关闭加载框
          this.isLoading = false;

          // 显示返回结果
          if (success) {
            this.$message({ type: 'success', message: msg });
            this.$router.back();
          } else {
            this.$message({ type: 'error', message: msg });
          }
        }
      });
    },
    // 返回事件
    cancel() {
      this.$router.back();
    },
  },
};
</script>
